package com.goldplusgold.tradedelay.app.my.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.goldplusgold.network.lib.AppCollectedInfoUtil;
import com.goldplusgold.network.lib.exception.ServerException;
import com.goldplusgold.support.lib.base.fragment.BaseFragment;
import com.goldplusgold.support.lib.utils.DeviceNetworkUtil;
import com.goldplusgold.support.lib.widget.AsyncTask;
import com.goldplusgold.tradedelay.app.R;
import com.goldplusgold.tradedelay.app.base.constant.IntentConstant;
import com.goldplusgold.tradedelay.app.my.networkservice.MyService;
import com.goldplusgold.tradedelay.app.my.account.UserInfo;
import com.goldplusgold.support.lib.utils.AppInfoUtils;
import com.goldplusgold.support.lib.utils.NetWorkConstant;
import com.goldplusgold.support.lib.utils.RegexUtils;
import com.goldplusgold.support.lib.widget.TitleView;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by admin on 2017/5/26.
 */

public class ResetForgotPasswordFragment extends BaseFragment implements Handler.Callback {
    @BindView(R.id.title_view)
    TitleView titleView;
    @BindView(R.id.et_pwd)
    EditText etPwd;
    @BindView(R.id.et_pwd_again)
    EditText etPwdAgain;
    @BindView(R.id.btn_login_again)
    Button btnLoginAgain;
    private String newLoginPwd;
    private String phone;
    private String code;
    private Handler handler = new Handler(this);

    public static ResetForgotPasswordFragment newInstance(String phone, String forgetPwdCode) {

        Bundle args = new Bundle();
        args.putString("phone", phone);
        args.putString("forgetPwdCode", forgetPwdCode);
        ResetForgotPasswordFragment fragment = new ResetForgotPasswordFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_reset_login_pwd;
    }

    @Override
    protected void initView() {
        super.initView();
        Bundle args = getArguments();
        if (args != null) {
            phone = args.getString(IntentConstant._PHONE);
            code = args.getString(IntentConstant._FORGET_PWD_CODE);
        }

        titleView.getTitletextView().setVisibility(View.VISIBLE);
        titleView.getTitletextView().setText("设置新密码");
        titleView.getBackView().setVisibility(View.VISIBLE);
    }


    @OnClick({R.id.iv_back, R.id.btn_login_again})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                getActivity().onBackPressed();
                break;
            case R.id.btn_login_again:
                newLoginPwd = etPwd.getText().toString().trim();
                String newPwdAgain = etPwdAgain.getText().toString().trim();
                if (TextUtils.isEmpty(newLoginPwd)) {
                    showToastMessage("请输入密码!", Toast.LENGTH_SHORT);
                    return;
                }
                if (TextUtils.isEmpty(newPwdAgain)) {
                    showToastMessage("请确认密码!", Toast.LENGTH_SHORT);

                    return;
                }
                if (!newLoginPwd.equals(newPwdAgain)) {
                    showToastMessage("两次输入的密码不一致!", Toast.LENGTH_SHORT);
                    return;
                }

                if (!RegexUtils.checkPassword(newLoginPwd)) {
                    showToastMessage(getString(R.string.password_format_promat), Toast.LENGTH_SHORT);
                    return;
                }
                String imei = DeviceNetworkUtil.getIMEIWrap(getContext());
                new ResetPwdCodeAsyncTask(imei).execute(AsyncTask.TYPE_NET);
                break;
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        int type = msg.what;
        switch (type) {
            case NetWorkConstant.NETWORK_ERROR_CODE:
                showToastMessage(R.string.network_error, Toast.LENGTH_LONG);
                break;
            case NetWorkConstant.NETWORK_SERVER_ERROR_CODE:
                String errorMessage = (String) msg.obj;
                showToastMessage(errorMessage, Toast.LENGTH_LONG);
                break;
        }
        return true;
    }

    public class ResetPwdCodeAsyncTask extends AsyncTask<Void, Void, UserInfo> {
        private String imei;

        public ResetPwdCodeAsyncTask(String imei) {
            this.imei = imei;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showLoadingControl();
        }

        @Override
        protected UserInfo doInBackground(Void... params) {
            try {
                UserInfo userInfo = MyService.getInstance().resetLoginPwd(newLoginPwd, phone, code, "android", imei, "android");
                if (userInfo != null) {
                    return userInfo;
                }
            } catch (ServerException e) {
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_SERVER_ERROR_CODE, e.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_ERROR_CODE, null);
            }
            return null;
        }

        @Override
        protected void onPostExecute(UserInfo userInfo) {
            super.onPostExecute(userInfo);
            dismisLoadingControl();
            if (userInfo != null) {
                String token = userInfo.getToken();
                if (!TextUtils.isEmpty(token)) {
                    String time = String.valueOf(System.currentTimeMillis());
                    String versionName = AppInfoUtils.getVersionName(getActivity().getApplicationContext());
                    AppCollectedInfoUtil.initAppCollectedInfo(getActivity().getApplicationContext(), token, time, versionName);
                }
                showToastMessage("密码修改成功", Toast.LENGTH_SHORT);
                finishActivity();
            }
        }
    }

    private void sendNetworkErrorMessage(int type, String errorMessage) {
        Message message = handler.obtainMessage();
        message.what = type;
        if (!TextUtils.isEmpty(errorMessage)) {
            message.obj = errorMessage;
        }
        handler.sendMessage(message);
    }
}
